using System;
using System.IO;
using WenYu.Core.Lexer;
using WenYu.Core.Parser;
using WenYu.Core.CodeGen;
using WenYu.Runtime;

namespace WenYu.CLI
{
    class Program
    {
        static int Main(string[] args)
        {
            if (args.Length == 0)
            {
                ShowHelp();
                return 0;
            }

            string command = args[0].ToLower();

            try
            {
                switch (command)
                {
                    case "run":
                        return HandleRun(args);
                    case "compile":
                        return HandleCompile(args);
                    case "lex":
                        return HandleLex(args);
                    case "--version":
                        ShowVersion();
                        return 0;
                    case "--help":
                    case "-h":
                        ShowHelp();
                        return 0;
                    default:
                        ShowHelp();
                        return 1;
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"❌ 错误: {ex.Message}");
                Console.ResetColor();
                return 1;
            }
        }

        static int HandleRun(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("❌ 缺少文件路径: wenyu run <file>");
                return 1;
            }

            string filePath = args[1];
            if (!File.Exists(filePath))
            {
                Console.WriteLine($"❌ 文件不存在: {filePath}");
                return 1;
            }

            try
            {
                string sourceCode = File.ReadAllText(filePath);
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine($"📂 加载: {filePath}");
                Console.ResetColor();

                // Lexer
                Console.WriteLine("[1/4] 词法分析...");
                var lexer = new WenYuLexer(sourceCode);
                var tokens = lexer.Tokenize();
                Console.WriteLine($"✅ {tokens.Count}个令牌");

                // Parser
                Console.WriteLine("[2/4] 语法分析...");
                var parser = new WenYuParser(tokens);
                var ast = parser.Parse();
                var errors = parser.GetErrors();
                if (errors.Count > 0)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine($"⚠️  解析警告/错误 ({errors.Count}个):");
                    foreach (var err in errors)
                        Console.WriteLine($"  {err}");
                    Console.ResetColor();
                }
                Console.WriteLine($"✅ 生成AST (含{ast.Statements.Count}条语句)");

                // CodeGen
                Console.WriteLine("[3/4] 代码生成...");
                var generator = new CodeGenerator();
                var instructions = generator.Generate(ast);
                Console.WriteLine($"✅ {instructions.Count}条指令");

                // Interpreter
                Console.WriteLine("[4/4] 执行...");
                Console.WriteLine("────────────────");
                var interpreter = new Interpreter(new YouthLibrary());
                interpreter.SetSymbolTable(generator.GetSymbolTable()); // 设置符号表以支持对象创建
                interpreter.Execute(instructions);
                Console.WriteLine("────────────────");
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("✅ 完成");
                Console.ResetColor();

                return 0;
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"❌ {ex.GetType().Name}: {ex.Message}");
                Console.ResetColor();
                return 1;
            }
        }

        static int HandleLex(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("❌ 缺少文件路径: wenyu lex <file>");
                return 1;
            }

            string filePath = args[1];
            if (!File.Exists(filePath))
            {
                Console.WriteLine($"❌ 文件不存在: {filePath}");
                return 1;
            }

            try
            {
                string sourceCode = File.ReadAllText(filePath);
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine($"📂 加载: {filePath}");
                Console.ResetColor();

                // Lexer
                Console.WriteLine("词法分析...");
                var lexer = new WenYuLexer(sourceCode);
                var tokens = lexer.Tokenize();
                
                Console.WriteLine($"\n✅ 共 {tokens.Count} 个令牌:\n");
                
                for (int i = 0; i < tokens.Count; i++)
                {
                    var token = tokens[i];
                    string typeColor = token.Type switch
                    {
                        TokenType.Keyword => "cyan",
                        TokenType.Identifier => "white",
                        TokenType.IntegerLiteral => "yellow",
                        TokenType.DoubleLiteral => "yellow",
                        TokenType.StringLiteral => "green",
                        TokenType.Operator => "magenta",
                        _ => "gray"
                    };
                    
                    Console.Write($"[{i,3}] ");
                    Console.ForegroundColor = token.Type switch
                    {
                        TokenType.Keyword => ConsoleColor.Cyan,
                        TokenType.Identifier => ConsoleColor.White,
                        TokenType.IntegerLiteral => ConsoleColor.Yellow,
                        TokenType.DoubleLiteral => ConsoleColor.Yellow,
                        TokenType.StringLiteral => ConsoleColor.Green,
                        TokenType.Operator => ConsoleColor.Magenta,
                        _ => ConsoleColor.Gray
                    };
                    Console.Write($"{token.Type,-20}");
                    Console.ResetColor();
                    Console.Write($" | ");
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.Write($"'{token.Value}'");
                    Console.ResetColor();
                    Console.WriteLine($" (行{token.Line}:列{token.Column})");
                }

                return 0;
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"❌ {ex.GetType().Name}: {ex.Message}");
                Console.ResetColor();
                return 1;
            }
        }

        static int HandleCompile(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("❌ 缺少文件路径: wenyu compile <file>");
                return 1;
            }

            string filePath = args[1];
            if (!File.Exists(filePath))
            {
                Console.WriteLine($"❌ 文件不存在: {filePath}");
                return 1;
            }

            try
            {
                string sourceCode = File.ReadAllText(filePath);
                var lexer = new WenYuLexer(sourceCode);
                var tokens = lexer.Tokenize();
                var parser = new WenYuParser(tokens);
                var ast = parser.Parse();
                var generator = new CodeGenerator();
                var instructions = generator.Generate(ast);

                string outputFile = Path.ChangeExtension(filePath, ".ir");
                using (var writer = new StreamWriter(outputFile))
                {
                    writer.WriteLine("; IR Code");
                    writer.WriteLine($"; From: {filePath}");
                    writer.WriteLine($"; Instructions: {instructions.Count}");
                    writer.WriteLine();
                    foreach (var instr in instructions)
                        writer.WriteLine(instr.ToString());
                }

                Console.WriteLine($"✅ 编译完成: {outputFile}");
                return 0;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ {ex.GetType().Name}: {ex.Message}");
                return 1;
            }
        }

        static void ShowVersion()
        {
            Console.WriteLine("文语 (WenYu) v1.0 MVP");
        }

        static void ShowHelp()
        {
            Console.WriteLine("📚 文语 (WenYu) - 编程语言编译器");
            Console.WriteLine("\n命令:");
            Console.WriteLine("  wenyu run <file>      编译并执行");
            Console.WriteLine("  wenyu compile <file>  仅编译");
            Console.WriteLine("  wenyu lex <file>      词法分析（调试）");
            Console.WriteLine("  wenyu --version       版本");
            Console.WriteLine("  wenyu --help          帮助");
        }
    }
}
